<?php

namespace app\api\controller;

use think\Controller;
use think\Request;
use qcloudcos\Cosapi;

/**
 * API 基类
 * 2017年5月31日 17:32:41
 * 权限检测、登录检测、API合法性
 * @吴家奕
 */

class Baseic extends Controller
{
    protected $api_code;             //	API编号
    protected $is_success = false;   //请求成功状态
    protected $code;                 //错误消息代码
    protected $msg;                  //错误信息
    protected $user_msg;             //用户提示信息
    protected $count = 0;            //数据总条数
    protected $cur_pages = 1;       //当前页码数
    protected $total_pages = 1;      //总页数
    protected $page_size = 15;      //每页数据记录数
    protected $is_login = false;    //当前登录状态
    protected $user_token;          //登录token
    protected $results;            //结果集
    protected $model;            //model类
    protected $status;            //创建房间返回状态
    protected $data = [];            //创建房间返回数据


    /**
     * 架构函数 取得模板对象实例
     * @access public
     */
    public function _initialize()
    {
        // 继承类控制器初始化
        if(method_exists($this,'__auto')){
           $this->__auto();
        }

        // $this->setApiCode();

        // $this->checkLogin();

        // $this->checkMethod();

        // $this->checkDevice();

    }

    /**
     * 登录状态
     * @access private
     */
    private function checkLogin(){
        $headerinfo = json_decode($this->request->header("X-Client-Event"));
        if (!is_null($headerinfo)){
          $this->user_token = $headerinfo->user_token;
        }
        else{
           $this->user_token = input('token');
        }
        if(isset($this->user_token)){
          $this->is_login = true;
        }
        unset($headerinfo);
    }

   /**
     * 检测请求设备的合法性
     * @access private
     */
    private function checkDevice(){
       $apiKey   = input('post.api_key');
       $apiCode  = input('post.api_code');
       $nowTime  = input('post.now_time');
       $thisTime = time();
       $postTime = $thisTime - $nowTime;

       // 密钥验证
       if($apiKey != md5($nowTime.'-'.$apiCode.'-'.config('salt'))){
          $this->restError('0003|请求秘钥错误');
          echo json_encode($this->returnResponse());
          unset($apiKey);
          unset($apiCode);
          unset($nowTime);
          unset($thisTime);
          unset($postTime);
          exit;
       }

       // 超时
       if($postTime >= 180000){
            $this->restError('0004|请求超过有效时间');
            echo json_encode($this->returnResponse());
            unset($apiKey);
            unset($apiCode);
            unset($nowTime);
            unset($thisTime);
            unset($postTime);
            exit;
       }

      //   if($apiCode !== $this->api_code){
      //     $this->restError('0005|请求API模块错误');
      //     echo json_encode($this->returnResponse());
      //     unset($apiKey);
      //     unset($apiCode);
      //     unset($nowTime);
      //     unset($thisTime);
      //     unset($postTime);
      //     exit;
      //  }
    }

    /**
     * 检测请求方式的合法性
     * @access private
     */
    private function checkMethod(){
     if (!$this->request->isPost()) {
         $this->restError('0002|非法请求');
         echo json_encode($this->returnResponse());
         exit;
      }
    }

    private function setApiCode(){
       $controller = request()->controller();
       $action     = request()->action();
       $this->api_code = $controller . '/' . $action;
       unset($controller);
       unset($action);
    }

    /**
     * 操作错误返回的快捷方法
     * @access protected
     * @param string $message 错误信息
     * @param integer $status 错误状态值
     * @return json[]
     * @author 吴家奕
     */
    protected function restError($msgCode = '0001|服务器繁忙')
    {
       $this->is_success = false;
       $messageCode      = explode("|", $msgCode);
       $this->code       = $messageCode[0];
       $this->msg        = $messageCode[1];
       unset($messageCode);
    }

    /**
     * 操作成功跳返回的快捷方法
     * @access protected
     * @param string $message 成功信息
     * @return json[]
     * @author 吴家奕
     */
    protected function restSuccess($msgCode = '0000|操作成功')
    {
       $this->is_success = true;
       $messageCode = explode("|", $msgCode);
       $this->code  = $messageCode[0];
       $this->msg   = $messageCode[1];
       unset($messageCode);
    }


    

    /**
     * 输出返回数据
     * @access protected
     * @param mixed $data 要返回的数据
     * @param String $type 返回类型 JSON XML
     * @param integer $code HTTP状态码
     * @return Response
     */
    protected function returnResponse()
    {
        $data['apiVersion']  = config('API_VERSION');
        $data['api_code']    = $this->api_code;
        $data['is_success']  = $this->is_success;
        $data['code']        = $this->code;
        $data['msg']         = $this->msg;
        $data['user_msg']    = $this->user_msg;
        $data['count']       = $this->count;
        $data['cur_pages']   = $this->total_pages;
        $data['total_pages'] = $this->total_pages;
        $data['page_size']   = $this->page_size;
        $data['is_login']    = $this->is_login;
        $data['user_token']  = $this->user_token;
        $data['results']     = $this->results;

        return $data;
    }


    /**
     * 操作错误返回的快捷方法
     * @access protected
     * @param string $message 错误信息
     * @param integer $status 错误状态值
     * @return json[]
     * @author 陈润璇
     */
    protected function Retterror($msgCode = '0|服务器繁忙|2000')
    {
        $messageCode = explode('|',$msgCode);
        $this->status = [
            'code'        =>  $messageCode['0'],
            'message'     =>  $messageCode['1'],
            'create_time' =>  time(),
            'err_code'    =>  $messageCode['2'],
        ];
        unset($messageCode);
    }

    /**
     * 操作成功跳返回的快捷方法
     * @access protected
     * @param string $message 成功信息
     * @return json[]
     * @author 陈润璇
     */
    protected function Rettsuccess($msgCode = '0000|操作成功')
    {   
       $messageCode = explode("|", $msgCode);
       $this->status  = [
           'code'  =>  $messageCode['0'],
           'message'  =>  $messageCode['1'],
           'create_time'  =>  time(),
       ];
       unset($messageCode);
    }

    
    /**
     * 输出返回数据
     * @access protected
     * @param mixed $data 要返回的数据
     * @param String $type 返回类型 JSON XML
     * @param integer $code HTTP状态码
     * @return Response
     * @author 陈润璇
     */
    protected function retResponse()
    {
        $data['status']  = $this->status;
        $data['data']    = $this->data;

        return json($data);
    }

    /**
    * 文件上传
    * @param File $file 传入参数
    * @return string 文件名
    * 
    * @author 陈润璇
    */
    protected function uplode($pic)
    {
        // 获取表单上传文件 例如上传了001.jpg
        $file = request()->file($pic);
        // 移动到框架应用根目录/public/uploads/ 目录下
        $info = $file->move(ROOT_PATH . 'public' . DS . 'uploads');
        if($info){

            $bucket = 'aks';
            $src = '../public/uploads/'.date('Ymd',time()).'/'.$info->getFilename();
            $dst = '/aks_class/'.$info->getFilename(); 
            Cosapi::setTimeout(180);
            Cosapi::setRegion('gz');
            $list = $ret->upload($bucket, $src, $dst);
            if($list['code'] == '0'){
                unlink($src);
            }else{
                unlink($src);
                return $this->error('图片上传有误');
            }
            $path[] = str_replace("file","cosgz",$list['data']['access_url']);
            return $path;
        }else{
            // 上传失败获取错误信息
            return $file->getError();
        }
    }
}
